package com.agilya.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import com.agilya.dao.daointerface.SachantDAO;
import com.agilya.dao.exception.DAOExceptions;
import com.agilya.modele.Sachant;
import com.sun.appserv.jdbc.DataSource;

@DAOSachant
public class JDBCSachantDAO implements SachantDAO {
	@Resource(name = "jdbc/QCMAgilya")
	private DataSource ds;

	@Override
	public boolean verifLogin(String email, String password) throws DAOExceptions {

		if (ds == null) {
			throw new DAOExceptions("Base de donnée non accessible. Data Source non initialisé");
		}

		try (Connection c = ds.getConnection(); PreparedStatement psmt = c.prepareStatement("SELECT MOT_DE_PASSE FROM SACHANT WHERE EMAIL = ? AND MOT_DE_PASSE =?");) {
			psmt.setString(1, email);
			psmt.setString(2, password);

			ResultSet rs = psmt.executeQuery();

			while (rs.next()) {
				return true;

			}

		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOExceptions(e.getMessage(), e);
		}

		return false;

	}

	@Override
	public Sachant getSachantByEmail(String email) throws DAOExceptions {
		if (ds == null) {
			throw new DAOExceptions("Base de donnée non accessible. Data Source non initialisé");
		}

		Sachant sachant = null;
		try (Connection c = ds.getConnection(); PreparedStatement psmt = c.prepareStatement("SELECT * FROM SACHANT WHERE EMAIL = ? ");) {
			psmt.setString(1, email);

			ResultSet rs = psmt.executeQuery();

			while (rs.next()) {

				int id = rs.getInt("ID_SACHANT");
				String nom = rs.getString("NOM");
				String prenom = rs.getString("PRENOM");
				String code = rs.getString("CODE");
				String motdepasse = rs.getString("MOT_DE_PASSE");

				sachant = new Sachant(id, nom, prenom, code, email, motdepasse);

			}

		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOExceptions(e.getMessage(), e);
		}

		return sachant;

	}
}
